package com.wuhuahe.luanfeng.netty.example.rpc;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created By wuhuahe
 * author:游龙
 * Date: 2018-07-14
 * Time: 16:51
 * Desc:
 */
@Service
public class ServiceMng implements ApplicationContextAware {

    private static ApplicationContext context;

    //所有提供的服务
    private static Map<String, Object> serviceMap = new HashMap<>();

    public static Object getService(String name) {
        return serviceMap.get(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
        Map<String, Object> beansMap = context.getBeansWithAnnotation(RpcClass.class);
        for (Map.Entry entry : beansMap.entrySet()) {
            String interfaceName = entry.getValue().getClass().getAnnotation(RpcClass.class).value().getName();
            serviceMap.put(interfaceName, entry.getValue());
        }
        if (!serviceMap.isEmpty()) {
            //ServiceCenter.register("DemoService", IPUtil.getLoaclIP()+"8080");
            RpcServer.startUp();
        }
    }

}
